/**
 * Oncut zentrale JavaScript Datei
 * Version 1.1
 */
$(document).ready(function() {
    // Austauschen des Play Buttons
    var playing = false;
    var pause   = false;
    currentSliderPositionIn = 0;
    currentSliderPositionOut = 0;

    /**
     * Init den Player mit allen notwendigen Funktionen
     */
    $.fn.initPlayer = function (){
        //console.log('init player');
        $.fn.playerSetup();
        $.fn.silderInOut();
        $.fn.addNewClip();
        $.fn.dynamicPlaylistScroller();
    }

    // - Player Anzeigen wenn er nicht schon sichtbar ist
    // - Befüllung des config Divs
    $.fn.playVideoFromPlaylist = function (videoId, videoPath){

        $('#col1_content').hide();
        $('#col1_PlayCutcontent').show();

        var playlist = [];
        playlist.push({'file': videoPath});

        $('#vId').html(videoId);//init Player new
        jwplayer().stop();
        jwplayer().load(videoPath);
        jwplayer().play();

    }

    /*Login*/
    $('#menu-setCutPlayer').click(function() {
        $('#col1_content').show();
        $('#col1_PlayCutcontent').hide();
    });


    /**
     * Player Setup
     */
    $.fn.playerSetup = function (){
        // jw-player laden wenn document bereit
        jwplayer("jw_player").setup({
               flashplayer: "http://192.168.2.3/workspaces/mklein/oncut/public/player/player.swf",
               controlbar: "bottom",
               skin: 'http://192.168.2.3/workspaces/pweil/oncut/public/player/skin/oncut.zip',
               file: 'http://192.168.2.3/workspaces/pweil/oncut/public/videos/fantastic.mp4',
               image: "http://192.168.2.3/workspaces/mklein/oncut/public/player/playerplatzhalter.jpg",
               width: 638,
               height: 359,
               setVolume:50,
               repeat: 'list',
               //stretching: 'none',
               events: {
                   onPlay: function(event){
                       playerObj.setInOut();
                       // Play Button Austausch
                       playing = true;
                       if(playing){
                           $('#controllbar .play').css('display', 'none');
                           $('#controllbar .pause').css('display', 'block');
                       }
                   },
                   onComplete: function(event){
                       // Play Button Austausch
                       //$('#controllbar .play').css('background', 'url(img/player/play_btn.gif)');
                       $('#controllbar .play').css('display', 'block');
                       $('#controllbar .pause').css('display', 'none');
                       // ENDE Play Button Austausch
                   },
                   onPause:function(event){
                       // Play Button Austausch
                       pause = true;
                       if(pause){
                          //$('#controllbar .play').css('background', 'url(img/player/play_btn.gif)');
                           $('#controllbar .play').css('display', 'block');
                           $('#controllbar .pause').css('display', 'none');
                       }
                   },
                   onMute:function(event){
                       //Mute Button
                       var mute = jwplayer('jw_player').getMute();

                       if(mute == true){
                           $('#controllbar .volumeBtn').css('background', 'url(img/player/volume_mute_btn.gif)');
                           $('#volumeSliderMute').css('display', 'block');
                           $('#volumeSlider').css('display', 'none');

                       }else{
                           $('#controllbar .volumeBtn').css('background', 'url(img/player/volume_btn.gif)');
                           $('#volumeSliderMute').css('display', 'none');
                           $('#volumeSlider').css('display', 'block');
                       }
                   }
            }
        });

        $('.playBtn').click(function() {
            $('#setInOutPoint').slider( "option", "values", [0, 0] );
            playerObj.setInOut();
        });

    }//player Setup ENDE


    /*
     * Sorttable und Slider
     */
    $.fn.silderInOut = function(){
        $(function() {
            // LoginBox
            $( "#logLink" ).click(function() {
                $( "#dialog-modal" ).dialog( "open" );
                return false;
            });

            $( "#volumeSlider" ).slider({
                range: "min",
                value:63 ,
                min: 0,
                max: 127,
                slide: function( event, ui ) {
                    var value = (ui.value);
                    var prozent = Math.floor((value/127)*100);
                    jwplayer().setVolume(prozent);
                }
            }).addTouch();

            $( "#setInOutPoint" ).slider({
                range: true,
                min: 0,
                max: 545,
                values: [0, 0],
                change: function( event, ui ) {
                    //playerObj.setInOutOnChange();
                    //playerObj.currentSliderPositionOut();
                    //playerObj.setInOut();

                },
                slide: function( event, ui ) {
                    /*$( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );*/
                    playerObj.setInOut();
                }
            }).addTouch();

            $( "#sortable" ).sortable({
                revert: true
            }).addTouch();
        });
    }//  ENDE Sorttable und Slider



    // <li> löschen wenn auf den x Button geklickt wird
    $('#sortable .delteliBtn').live('click', function() {
        $(this).closest('li').remove();
        $.fn.dynamicPlaylistScroller();
    });

    $.fn.addNewClip = function(){
        // Mini Playliste der Clips die geschnitten wurden mit entsprechenden Thumbs
        $('#controllbar .neuerClip').on('click', function() {

            //Nur einfügen wenn es auch eine Cliplänge gibt
            if(parseFloat($('#totalPointsTime').html().replace(/:|\./gi, "") ) != 0 ){
                $.ajax({
                    url: 'http://192.168.2.3/workspaces/mklein/oncut/public/videoengine/framepic/',
                    data: 'start=' + $('#inPointTime').children('span').html()+"&vId="+$('#vId').html(),
                    type: 'GET',
                    timeout: 30000,
                    dataType: 'json',
                    error:function (xhr, ajaxOptions, thrownError){
                        alert('Error loading json data! instId');
                    },
                    success: function(json){

                        $("#sortable").append(  '<li>' +
                                                '<div class="ready"><img width="96" height="53" src="img/tmp/'+json.keyframe+'" /></div>' +
                                                '<div class="delteBox"><p>'+$('#inPointTime').html()+'</p><div class="delteliBtn"></div></div>' +
                                                '<div class="vConfig" style="display: none">' +
                                                    '<div class="vId">'+$('#vId').html()+'</div>' +
                                                    '<div class="vStart">'+$('#inPointTime').children('span').html()+'</div>' +
                                                    '<div class="vDuration">'+$('#totalPointsTime').html()+'</div>' +
                                                    '<div class="vName">'+json.vName+'</div>' +
                                                    '<div class="vThumb">img/tmp/'+json.keyframe+'</div>' +
                                                '' +
                                                '</li>');

                        $.fn.dynamicPlaylistScroller();
                        // Hover Funktion fuer neue Element
                        hover();
                        // ENDE Hover Funktion fuer neue Element
                    }
                });
            }

        });
    }// ENDE Scroller dynamic width and delte Funktion

    /**
     * aus dem Gespeicherten Json Object die Playliste erzeugen
     */
    $.fn.createPlaylistFromJson = function(){
        //Nur einfügen wenn es auch eine Cliplänge gibt

        $.ajax({
            url: 'http://192.168.2.3/workspaces/mklein/oncut/public/videoengine/getplaylist/',
            data: 'projectId=1' ,
            type: 'GET',
            timeout: 30000,
            dataType: 'json',
            error:function (xhr, ajaxOptions, thrownError){
                alert('Error loading json data! instId');
            },
            success: function(json){

                //console.log(json);
                // Inhalt vorher leeren
                $("#sortable").html('');
                for (p in json) {

                    $("#sortable").append(  '<li>' +
                                            '<div class="ready"><img width="96" height="53" src="'+json[p].vThumb+'" /></div>' +
                                            '<div class="delteBox"><p>'+json[p].vStart+'</p><div class="delteliBtn"></div></div>' +
                                            '<div class="vConfig" style="display: none">' +
                                                '<div class="vId">'+json[p].vId+'</div>' +
                                                '<div class="vStart">'+json[p].vStart+'</div>' +
                                                '<div class="vDuration">'+json[p].vDuration+'</div>' +
                                                '<div class="vName"></div>' +
                                                '<div class="vThumb">'+json[p].vThumb+'</div>' +
                                            '' +
                                            '</li>');

                }
                $.fn.dynamicPlaylistScroller();
                // Hover Funktion fuer neue Element
                hover();
                // ENDE Hover Funktion fuer neue Element
            }
        });

    }// ENDE aus dem Gespeicherten Json Object die Playliste erzeugen


    /**
     * Oncut Clipliste speichern
     */
    $.fn.saveProjectList = function(){

        //Nur einfügen wenn es auch eine Cliplänge gibt
        var jsonObjFav = [];
        $('#projectList .clips').each(function(index) {
            var id = $(this).attr('id').replace(/clipId/, '');
            jsonObjFav.push({'vId' : id });
        });

        var jsonObjClips = [];

        $('#sortable li .vConfig').each(function(index) {
            jsonObjClips.push({'vId': $(this).children(".vId").html(), 'vStart': $(this).children(".vStart").html(), 'vDuration': $(this).children(".vDuration").html(), 'vThumb': $(this).children(".vThumb").html()});
        });
//console.log(jsonObjClips);


        $.post("http://192.168.2.3/workspaces/mklein/oncut/public/videoengine/saveprojectlist?pId=1", {'jsonObjFav' : jsonObjFav, 'jsonObjClips' : jsonObjClips}, function(res){});

    }// ENDE aus dem Gespeicherten Json Object die Playliste erzeugen



    // Berechnung des Dynamischen Playlist Scrollers
    $.fn.dynamicPlaylistScroller = function (){
        var liWidth = $('#playlist #sortable').children().width();
        var listItems = $('#playlist #sortable').children().length;
        var scrollWidth = (((liWidth * listItems) + (listItems*38))+10);

        $('#playlist .scroll-pane .scroll-content').css('width', scrollWidth);

        if(scrollWidth < 638){
            $('#playlist .scroll-pane').removeClass('horizontalScroll');
        }else{
            $('#playlist .scroll-pane').addClass('horizontalScroll');
        }
    }
    // ENDE Berechnung des Dynamischen Playlist Scrollers



    // read More expander Funktion
     $('div.content p').expander({
        slicePoint:       90,  // default is 100
        expandPrefix:     ' ', // default is '... '
        expandText:       '... mehr', // default is 'read more'
        collapseTimer:    25000, // re-collapses after 5 seconds; default is 0, so no re-collapsing
        userCollapseText: '[^]'  // default is 'read less'
     });
    // ENDE read More expander Funktion






    /*
        Klasse Flex hinzufügen um die Listenansicht
        in der rechten Spalte zu aendern
    */
    $('.switch p.list').click(function(){
        $('#page_margins').removeClass('flex');
        $('.switch p.tile').removeClass('active');
        $(this).addClass('active');
    });
    $('.switch p.tile').click(function(){
        $('#page_margins').addClass('flex');
        $('.switch p.list').removeClass('active');
        $(this).addClass('active');
    });
    //ENDE Listenansicht Klassen

    if($('#col1_PlayCutcontent').html() != null){
        //console.log($('#col1_PlayCutcontent').html());
        $.fn.initPlayer();
    }
}); // ENDE $(document).ready


    // mouseover
    function hover(){
        $('#sortable li').mouseenter(function() {
            $(this).children('.ready').addClass('relative');
            $(this).children('.ready').append('<span class="hoverBox"></span>');
            $(this).children('.ready').append('<span class="hoverPic"></span>');
            $('#sortable .hoverClip').css('display', 'block');
        });

        $('#sortable li').mouseleave(function() {
            $('#sortable li .ready span').remove();
            $(this).children('.ready').removeClass('relative');
            $('#sortable .hoverClip').css('display', 'none');
        });
    }
    // ENDE mouseover


    // Playlist JSON
    var playlist = [];

    $.fn.newPlaylist = function (){

        var jsonObj = [];

        $('#sortable li .vConfig').each(function(index) {

            var startSplit   = $(this).children(".vStart").html().split(':');
            var startSeconds = startSplit[0] * 3600 +startSplit[1] * 60 + parseFloat(startSplit[2]);
            var endSplit     = $(this).children(".vDuration").html().split(':');
            var endSeconds   = (endSplit[0] * 3600) + (endSplit[1] * 60) + endSplit[2] ;
                endSeconds   =  parseFloat(startSeconds) + parseFloat(endSeconds);
            var videoName    = $(this).children(".vName").html();

            //console.log(startSeconds);

            if( startSeconds > 0 ){
                startSeconds = startSeconds.toString().replace('.', ',');
            }
            if( endSeconds > 0 ){
                endSeconds   = endSeconds.toString().replace(".", ',');
            }
            jsonObj.push({'file':'http://192.168.2.3/workspaces/mklein/oncut/public/videos/'+videoName+'?start='+startSeconds+'&end='+endSeconds});

        });

        jwplayer().load(jsonObj);
        jwplayer().play();
    }

    /**
     *  Auslesen der Clips und als JSON zu PHP schicken
     *  zur Abarbeitung im Backend
     */
    $.fn.buildVideoObj = function (){

        var jsonObj = [];

        $('#sortable li .vConfig').each(function(index) {
            jsonObj.push({'vId': $(this).children(".vId").html(), 'vStart': $(this).children(".vStart").html(), 'vDuration': $(this).children(".vDuration").html(), 'vThumb': $(this).children(".vThumb").html()});
        });

        //Daten ans ZF schicken zur weiterverarbeitung
        $.post("http://192.168.2.3/workspaces/mklein/oncut/public/videoengine/receiveplaylist?pId=1", {data: jsonObj}, function(res){});
    }


    /**
    * Add Fav Video
    */
    $.fn.setFavVideo = function (id){

        $.ajax({
            url: 'http://192.168.2.3/workspaces/mklein/oncut/public/ajax/setfavvideo/',
            data: 'video_nid='+id ,
            type: 'GET',
            timeout: 30000,
            dataType: 'json',
            error:function (xhr, ajaxOptions, thrownError){
                alert('Error loading json data! instId');
            },
            success: function(json){

                if ($('#clipId'+json[0].video_nid).length == 0) {
                    var element = "";

                    element += '<div class="clips" id="clipId'+json[0].video_nid+'">';
                    element += '    <div class="thumClip">';
                    element += '        <img src="img/videothumbs/'+json[0].video_filename+'.jpg" width="96" height="53" alt="Mercedes" />';
                    //element += '        <div class="hdContainer"><span class="quali">HD+</span><span class="time"><?php echo date('H:i:s', mktime(0,0,$row['video_duration'],0,0,0)); ?> </span></div>';
                    element += '        <div class="hdContainer"><span class="quali">HD+</span><span class="time"></span></div>';
                    element += '    </div>';
                    element += '    <div class="txt">';
                    element += '        <p class="subline">'+json[0].vid_video2lang_name+'</p>';
                    element += '        <p class="lang"><span>Sprache:</span> Deutsch + Englisch</p>';
                    element += '    </div>';
                    element += '    <div class="button">';
                    element += '        <script type="text/javascript">';
                    //element += '        var playlist'+json[0].video_nid+' = [];';
                    //element += '        playlist'+json[0].video_nid+'.push({"file": "'+json[0].frontendVideoPath+''+json[0].video_filename+'.mp4"});';
                    element += '        </script>';
                    element += '       <div class="downloadBtn" title="Download"></div>';
                    element += '       <div class="playBtn" title="Play" onclick="$.fn.playVideoFromPlaylist('+json[0].video_nid+', \''+json[0].frontendVideoPath+json[0].video_filename+'\'.mp4\')"></div>';
                    element += '        <div class="deleteBtn" title="Löschen" onclick="$.fn.unsetFavVideo('+json[0].video_nid+');"></div> </div>';
                    element += '   <div class="content">';
                    element += '       <p>'+json.vid_video2lang_short_desc+'</p>';
                    element += '   </div>';
                    element += '</div>';

                    $("#projectList").append(element);


                }

                $('#liPClips').animate({ backgroundColor: "#00DAFA" }, 'slow');
                $('#liPClipsHref').html('Hinzugefügt');

                $('#liPClips').animate(
                    {backgroundColor: "#002126" },
                    {duration: 'slow', complete:function(){
                        $('#liPClipsHref').html('Projekt Clips');
                    }
                });


            }
        });

    }

    /*
    * Delete Fav Video
    */
    $.fn.unsetFavVideo = function (){

    }


    /**
     * Switcher für die Clips und Projekt Clips
     */
    $.fn.toggelClipNav = function (id){

        if(id == "clips"){
            $('#liClips').addClass('active');
            $('#liPClips').removeClass('active');

            $('#clipsList').show();
            $('#projectList').hide();

        }else{
            $('#liPClips').addClass('active');
            $('#liClips').removeClass('active');

            $('#clipsList').hide();
            $('#projectList').show();

        }

        $('.mainMenu .navigation li').click(function() {
            $('.mainMenu .navigation li').addClass('active');
        });

    }




    /*Login*/
    $('#logFirst #logLink').click(function() {
        $('#logFirst').css('display', 'none');
        $('#logFirstForm').css('display', 'block');
    });


    $('#loginClose').click(function() {
        $('#logFirst').css('display', 'block');
        $('#logFirstForm').css('display', 'none');
    });

/*    if($('#form_user_login').hasClass('error')){
        $('#logFirst').css('display', 'none');
        $('#logFirstForm').css('display', 'none');
        $('#error-message').show();
    }*/

   /* $('#goLogin').click(function() {
        $('#logFirst').css('display', 'none');
        $('#logFirstForm').css('display', 'block');
       *//* $('#error-message').hide();*//*
    });*/

/**
 * E-Mail Adressen Verschluessleung
 */
function UnCryptMailto(s) {
    var n = 0;
    var r = "";
    for( var i = 0; i < s.length; i++) {
        n = s.charCodeAt( i );
        if( n >= 8364 ) {
            n = 128;
        }
        r += String.fromCharCode( n - 1 );
    }
    return r;
}

function linkTo_UnCryptMailto( s ) {
    location.href=UnCryptMailto( s );
}
